package com.qqt.csr.archive.batch.task.etl.writer;

import cn.hutool.json.JSONUtil;
import com.qqt.csr.archive.entity.writer.ArchiveConversation;
import com.qqt.csr.archive.service.ArchiveConversationService;
import com.qqt.csr.archive.service.CsrImAccountService;
import com.qqt.csr.common.utils.CacheKeyUtil;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.batch.item.Chunk;
import org.springframework.batch.item.ItemWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author: yang hao
 * @Date: 2024/11/20 10:20
 * @Description: 会话归档 写入器
 **/
@Slf4j
@Component
@SuppressWarnings("unused")
public class ConversationArchiveWriter implements ItemWriter<ArchiveConversation> {

    @Autowired
    private ArchiveConversationService archiveConversationService;

    @Autowired
    private CsrImAccountService csrImAccountService;

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 批量写入
     * @param chunk {@link ArchiveConversation} 批量上下文
     */
    @Override
    public void write(@NonNull Chunk<? extends ArchiveConversation> chunk) {
        log.debug("开始写入归档会话数据, 会话列表：{}", JSONUtil.toJsonStr(chunk.getItems()));
        List<ArchiveConversation> conversations = chunk.getItems().stream()
                .map(item -> {
                    // 缓存会话 1分钟过期
                    redissonClient.getBucket(String.format(CacheKeyUtil.Archive.CONVERSATION_ARCHIVE, item.getConversationId()))
                            .setAsync(JSONUtil.toJsonStr(item), CacheKeyUtil.EXPIRE_TIME_1M, TimeUnit.MILLISECONDS);
                    return (ArchiveConversation)item;
                })
                .toList();
        archiveConversationService.saveBatch(conversations);
        log.debug("写入归档会话数据成功, 会话数量:{}", chunk.getItems().size());
    }

}
